<!-- 安全管理-改善管理页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common equip-inspect-rule-list-page">
      <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="改善内容" prop="improveName">
              <px-input v-model="queryParams.improveName" placeholder="请输入改善内容/编号" clearable />
            </px-form-item>
          </px-col>
          <!-- 科室 -->
          <px-col :span="6">
            <EquipClassSelect :className="queryParams.className" @changeClassName="changeClassName" />
          </px-col>
          <!--  系统-->
          <px-col :span="6">
            <EquipSystemTree
              :className="queryParams.className"
              :systemCode="queryParams.systemCode"
              @changeAllSystemCodes="changeAllSystemCodes"
              @changeSystemCodes="changeSystemCodes"
              @clearSystem="clearSystem"
            />
          </px-col>
          <px-col :span="6">
            <px-form-item label="原因类型">
              <px-select v-model="queryParams.reasonType" placeholder="请选择原因类型" filterable clearable>
                <px-option v-for="(item, index) in missingLevelList" :key="index" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="改善必要性">
              <px-select v-model="queryParams.necessaryLevel" placeholder="请选择改善必要性" filterable clearable>
                <px-option v-for="(item, index) in missingTypeList" :key="index" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="新建厂follow">
              <px-select v-model="queryParams.newFactoryFlag" placeholder="请选择新建厂follow" filterable clearable>
                <px-option v-for="(item, index) in reportUserList" :key="index" :label="item.label" :value="item.name" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="记录人">
              <px-select-v2 v-model="queryParams.recorder" filterable clearable :options="computedMissingOwnerList" placeholder="请选择记录人" />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="改善状态">
              <px-select v-model="queryParams.improveStatus" placeholder="请选择改善状态" filterable clearable>
                <px-option v-for="(item, index) in missingResourceList" :key="index" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn" style="display: flex; justify-content: space-between">
        <div><px-button v-has="'ALL_SAFEMANAGE_IMPROVE_ADD'" type="primary" @click="handleAdd">新增改善管理</px-button></div>
        <div><px-button type="primary" @click="queryTable">查询</px-button> <px-button @click="resetTable">重置</px-button></div>
      </div>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 355px)" border>
        <px-table-column label="序号" width="80" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">
            <px-button v-if="item.improveId" link type="primary" @click="handleView(scope.row)">
              {{ scope.row.improveId }}
            </px-button>
            <span v-else-if="item.newFactoryFlag">
              <span v-if="scope.row.newFactoryFlag === 'Y'"> 是 </span>
              <span v-if="scope.row.newFactoryFlag === 'N'"> 否 </span>
            </span>
            <span v-else-if="item.improveStatus">
              <px-tag
                v-if="scope.row.improveStatus"
                effect="plain"
                :style="{
                  color: `${tagColorList[scope.row.improveStatus]}`,
                  border: `1px solid ${tagBorderColorList[scope.row.improveStatus]}`,
                  backgroundColor: `${tagBgColorList[scope.row.improveStatus]}`
                }"
              >
                {{ scope.row.improveStatus }}
              </px-tag>
              <span v-else>-</span>
            </span>
            <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
          </template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" width="120" align="center">
          <template #default="scope">
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'ALL_SAFEMANAGE_IMPROVE_VIEW'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.recorder === user" content="编辑" placement="top">
              <px-button v-has="'ALL_SAFEMANAGE_IMPROVE_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.recorder === user" content="删除" placement="top">
              <px-button v-has="'ALL_SAFEMANAGE_IMPROVE_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="inspection-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 详情新增/编辑页面 -->
    <AddDefectDetail
      :relationNumber="relationNumber"
      :drawerType="drawerType"
      :isMain="isMain"
      :isView="isView"
      :missingId="improveId"
      :missingLevelList="missingLevelList"
      :missingTypeList="missingTypeList"
      :missingResourceList="missingResourceList"
      :missingOwnerList="missingOwnerList"
      :rectifyStatusList="rectifyStatusList"
      :reportUserList="reportUserList"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <!-- 详情查看页面 -->
    <ViewDefectDetail
      :isMain="isMain"
      :isView="isView"
      :missingId="improveId"
      :missingLevelList="missingLevelList"
      :missingTypeList="missingTypeList"
      :missingResourceList="missingResourceList"
      :rectifyStatusList="rectifyStatusList"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_SAFEMANAGE_IMPROVE"
});
import { queryEnum, queryImprove, updateImprove } from "@/api/equip/improve";
import { useNav } from "@/layout/hooks/useNav";
import { getToken } from "@/utils/auth";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import axios from "axios";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, onMounted, reactive, toRefs } from "vue";
import { useRoute } from "vue-router";
import AddDefectDetail from "./components/AddDefectDetail.vue";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import ViewDefectDetail from "./components/ViewDefectDetail.vue";
const route = useRoute();

// 获取详情接口
const getDetail = async () => {
  axios({
    method: "post",
    url: "/ifp/digitaltwins/api/v1/improve/get",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + getToken().accessToken || ""
    },
    data: {
      relationNumber: relationNumber.value
    }
  }).then(res => {
    if (res?.data?.success) {
      if (res.data.data.relationNumber === relationNumber.value) {
        //详情
        improveId.value = res.data.data.improveId;
        isMain.value = false;
        isView.value = true;
      }
    } else {
      // 新增
      drawerType.value = "add";
      isMain.value = false;
      isView.value = false;
    }
  });
};

const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    className: "",
    systemCodes: "",
    improveName: "",
    systemName: "",
    reasonType: "",
    necessaryLevel: "",
    newFactoryFlag: "",
    improveStatus: ""
  },
  tableColumns: [
    { prop: "improveId", label: "改善编号", minWidth: "180", showOverflowTooltip: true, fixed: "left", improveId: true },
    { prop: "className", label: "科室", minWidth: "100", showOverflowTooltip: true },
    { prop: "systemName", label: "系统", minWidth: "150", showOverflowTooltip: true },
    { prop: "improveName", label: "改善内容", minWidth: "180", showOverflowTooltip: true },
    { prop: "reasonType", label: "原因类型", minWidth: "100", showOverflowTooltip: true },
    { prop: "necessaryLevel", label: "改善必要性", minWidth: "100", showOverflowTooltip: true },
    { prop: "newFactoryFlag", label: "新建厂follow", minWidth: "110", showOverflowTooltip: true, newFactoryFlag: true },
    { prop: "recorder", label: "记录人", minWidth: "100", showOverflowTooltip: true },
    { prop: "createTime", label: "创建日期", minWidth: "150", showOverflowTooltip: true },
    { prop: "improveStatus", label: "状态", minWidth: "90", showOverflowTooltip: true, improveStatus: true }
  ],
  tableData: [],
  total: 0,
  systemCodes: [],
  missingLevelList: [],
  missingTypeList: [],
  missingResourceList: [],
  rectifyStatusList: [],
  reportUserList: [
    { name: "Y", label: "是" },
    { name: "N", label: "否" }
  ],
  missingOwnerList: [],
  drawerType: "add",
  improveId: "",
  relationNumber: "", //接受缺失管理传过来的参数
  user: ""
});
const {
  isMain,
  isView,
  queryParams,
  tableColumns,
  tableData,
  total,
  systemCodes,
  missingLevelList,
  missingTypeList,
  missingResourceList,
  rectifyStatusList,
  reportUserList,
  missingOwnerList,
  drawerType,
  improveId,
  relationNumber,
  user
} = toRefs(state);

const tagColorList = {
  未开始: "#f59e0b", // 未响应
  进行中: "#3b82f6", // 待整改
  已完成: "#10b981" // 整改中
};
const tagBorderColorList = {
  未开始: "#fce2b6", // 未响应
  进行中: "#c6e2ff", // 待整改
  已完成: "#b7ead9" // 整改中
};
const tagBgColorList = {
  未开始: "#fef5e6", // 未响应
  进行中: "#ecf5ff", // 待整改
  已完成: "#e8f8f3" // 整改中
};

// 进入页面时触发
onMounted(() => {
  //判断按钮权限
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  user.value = `${userInfo.username}-${userInfo.realName}`;
  if (route?.query && route?.query?.id) {
    relationNumber.value = route?.query?.id;
    getDetail();
    querySelect();
  } else {
    isMain.value = true;
    isView.value = true;
    querySelect();
    queryTable();
    focusRecorder();
  }
});
//获取recorder下拉框
const computedMissingOwnerList = computed(() => {
  return missingOwnerList.value.map(item => {
    return {
      label: item.label,
      value: item.label,
      key: item.empNo
    };
  });
});
// 查询备件列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  params.systemCodes = systemCodes.value;
  const data = await queryImprove(params);
  tableData.value = data?.data || [];
  total.value = data?.total;
};
// 获取下拉框
const querySelect = async () => {
  const list: any = await queryEnum();
  //原因名称
  missingLevelList.value = Object.keys(list?.REASON_TYPE).map((item, index) => ({
    id: index + 1,
    value: item,
    name: list?.REASON_TYPE[item]
  }));
  //改善必要性
  missingTypeList.value = Object.keys(list?.NECESSARY_LEVEL).map((item, index) => ({
    id: index + 1,
    value: item,
    name: list?.NECESSARY_LEVEL[item]
  }));
  //改善状态
  missingResourceList.value = Object.keys(list?.IMPROVE_STATUS).map((item, index) => ({
    id: index + 1,
    value: item,
    name: list?.IMPROVE_STATUS[item]
  }));
  //改善来源
  rectifyStatusList.value = Object.keys(list?.IMPROVE_RESOURCE).map((item, index) => ({
    id: index + 1,
    value: item,
    name: list?.IMPROVE_RESOURCE[item]
  }));
};
// 获取当前科室记录人接口
const focusRecorder = async (val?) => {
  const param = queryParams.value.className ? [queryParams.value.className] : [];
  const data = await getEmployeeIdAndName(param);
  missingOwnerList.value = JSON.parse(JSON.stringify(data));
};

// 重置筛选条件和备件列表
const resetTable = async () => {
  queryParams.value = {
    className: "",
    improveName: "",
    systemCodes: "",
    systemName: "",
    systemId: "",
    reasonType: "",
    necessaryLevel: "",
    newFactoryFlag: "",
    improveStatus: "",
    recorder: "",
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  systemCodes.value = [];
  queryTable();
  focusRecorder();
};

// 查看改善管理
const handleView = (row: any) => {
  improveId.value = row.improveId;
  isMain.value = false;
  isView.value = true;
};
//新增改善管理
const handleAdd = () => {
  drawerType.value = "add";
  isMain.value = false;
  isView.value = false;
};
// 编辑改善管理
const handleEdit = (row: any) => {
  drawerType.value = "edit";
  improveId.value = row.improveId;
  isMain.value = false;
  isView.value = false;
};
// 删除改善管理
const handleDelete = async (row: any) => {
  PxMessageBox.confirm("要删除当前改善管理吗？", "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await updateImprove({
        improveId: row.improveId,
        status: "INVALID"
      });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  isMain.value = true;
  relationNumber.value = "";
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = async val => {
  queryParams.value.className = val;
  queryParams.value.systemCode = "";
  systemCodes.value = [];
  queryParams.value.recorder = "";
  focusRecorder(val);
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  queryParams.value.systemCode = val;
  systemCodes.value = val2;
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  queryParams.value.className = val2;
  queryParams.value.systemCode = val3;
  systemCodes.value = val4;
};
// 系统组件值改变触发
const clearSystem = val => {
  queryParams.value.systemCode = "";
  systemCodes.value = [];
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");
</style>
